﻿using System;
using System.Data;
using System.Windows.Forms;
using HRM.HRMServiceProxy;
using WeifenLuo.WinFormsUI.Docking;
using System.Drawing;
using System.Collections.Generic;
using RateInfo = HRM.BusinessLogic.RateInfo;
using HeaderInfo = HRM.BusinessLogic.BhHeaderInfo;
using DetailInfo = HRM.BusinessLogic.BhDetailInfo;
using HRM.BusinessLogic;

namespace HRM
{
    public partial class frmGetNewDataList_TS : FormBase
    {
        DialogResult dlgResult;
        RoleRightInfo listRole;
        int itemCount = 0;
        int pageSize = UIParamater.pageSize;
        int totalPage = 0;
        int currPage = 0;
        int branch_ID;
        int department_ID;
        string _selectedID = ",";
        DataTable _dtTS = null;
        Int64 DocumentId = 0; //Kỳ phát sinh bảo hiểm
        PositionDetailInfo _PDInfo;
        PositionDetailClient _wcfPositionDetal;
        HeaderInfo _HeaderInfo = null;
        public DataTable dtTS
        {
            get { return _dtTS; }
            set { _dtTS = value; }
        }

        public string SelectedID
        {
            get { return _selectedID; }
            set { _selectedID = value; }
        }
        private string _FullName;
        public string FullName
        {
            get { return _FullName; }
            set { _FullName = value; }
        }
        string _Code;
        public string Code
        {
            get { return _Code; }
            set { _Code = value; }
        }
        private int _EmployeeID;
        public int EmployeeID
        {
            get { return _EmployeeID; }
            set { _EmployeeID = value; }
        }
        string _SIBookNo;
        public string SIBookNo
        {
            get { return _SIBookNo; }
            set { _SIBookNo = value; }
        }

        public override void Show_Form()
        {
            this.Show();
        }

        public DialogResult Show_Form(object obj)
        {
            return this.ShowDialog();
        }

        EmployeeClient _wcfEmployee;
        public frmGetNewDataList_TS()
        {
            InitializeComponent();
            dlgResult = DialogResult.Cancel;
            _wcfEmployee = Service.Employee();
            txtKeyWord.Focus();
            branch_ID = Program.intBranchID;
            //BuildVoucherGrid();
            //LoadData();
        }

        Decimal BhxhRate, BhytRate, BhtnRate = 0;
        DateTime ViewDate;
        //
        public frmGetNewDataList_TS(HeaderInfo headerInfo, Decimal bhxhRate, Decimal bhytRate, Decimal bhtnRate, DateTime _ViewDate)
        {
            InitializeComponent();
            dlgResult = DialogResult.Cancel;
            _wcfEmployee = Service.Employee();
            txtKeyWord.Focus();
            //listRole = _listRole;
            branch_ID = Program.intBranchID;
            DocumentId = headerInfo.Document_Id;
            //BuildVoucherGrid();
            //LoadData();
            _HeaderInfo = headerInfo;
            BhxhRate = bhxhRate;
            BhytRate = bhytRate;
            BhtnRate = bhtnRate;
            ViewDate = _ViewDate;
        }

        protected override void Init_Control()
        {
            //

            _wcfEmployee = Service.Employee();
            _wcfPositionDetal = Service.PositionDetail();
            //
            Init_Grid();
            LoadData();
        }

        //Khởi tạo danh sách cho grid
        DataGridHandle m_GridHandle;
        protected void Init_Grid()
        {
            List<DataGridViewColumn> arrColumn = new List<DataGridViewColumn>();
            arrColumn.Add(FormGlobals.Grid_NewColumn<DataGridViewCheckBoxColumn>("Chọn", "Check", 50));
            //
            arrColumn.Add(FormGlobals.Grid_NewColumn<DataGridViewTextBoxColumn>("STT", "RowNumber", 50));
            arrColumn.Add(FormGlobals.Grid_NewColumn<DataGridViewTextBoxColumn>("Họ và tên", "Employee_FullName", 120));
            arrColumn.Add(FormGlobals.Grid_NewColumn<DataGridViewTextBoxColumn>("Ngày sinh", "Employee_DateOfBirth", 90, Globals.CS_DISPLAY_DATE_FORMAT));
            arrColumn.Add(FormGlobals.Grid_NewColumn<DataGridViewTextBoxColumn>("Số sổ BH", "Detail_InsBookNo", 80));
            arrColumn.Add(FormGlobals.Grid_NewColumn<DataGridViewTextBoxColumn>("Từ tháng", "Detail_FromDate", 70, Globals.CS_DISPLAY_MONTHYEAR_FORMAT));
            arrColumn.Add(FormGlobals.Grid_NewColumn<DataGridViewTextBoxColumn>("Đến tháng", "Detail_ToDate", 70, Globals.CS_DISPLAY_MONTHYEAR_FORMAT));
            arrColumn.Add(FormGlobals.Grid_NewColumn<DataGridViewTextBoxColumn>("Số tháng", "Detail_TotalMonth", 60));
            arrColumn.Add(FormGlobals.Grid_NewColumn<DataGridViewTextBoxColumn>("Mức lương", "Detail_TotalAmount", 40));
            arrColumn.Add(FormGlobals.Grid_NewColumn<DataGridViewTextBoxColumn>("ID", "Employee_ID", 0));
            arrColumn.Add(FormGlobals.Grid_NewColumn<DataGridViewTextBoxColumn>("Ghi chú", "GhiChu", 200));
            arrColumn.Add(FormGlobals.Grid_NewColumn<DataGridViewTextBoxColumn>("Chức danh", "Detail_PositionName", 0));
            //
            m_GridHandle = FormGlobals.Grid_Init(dgvEmployeeList, arrColumn, "", 1);
            //dgvEmployeeList.CellValidating += new DataGridViewCellValidatingEventHandler(dgvEmployeeList_CellValidating);
            dgvEmployeeList.CellContentClick += new DataGridViewCellEventHandler(dgvEmployeeList_CellContentClick);
        }

        void dgvEmployeeList_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            if (dgvEmployeeList.Columns[e.ColumnIndex].Name.ToUpper() == "CHECK")
            {
                if (Globals.DB_GetValue<Boolean>(dgvEmployeeList.Rows[e.RowIndex].Cells["CHECK"].Value))
                {
                    if (Globals.DB_GetValue<int>(dgvEmployeeList.Rows[e.RowIndex].Cells["Detail_TotalMonth"].Value) > 7)
                    {
                        dgvEmployeeList.Rows[e.RowIndex].Cells["CHECK"].Value = false;
                    }
                }
            }
        }

        void dgvEmployeeList_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
        {
            //if(dgvEmployeeList.Columns[e.ColumnIndex].Name.ToUpper() == "CHECK")
            //{
            //    if (Globals.DB_GetValue<Boolean>(dgvEmployeeList.Rows[e.RowIndex].Cells["CHECK"].Value))
            //    {
            //        if (Globals.DB_GetValue<int>(dgvEmployeeList.Rows[e.RowIndex].Cells["Detail_TotalMonth"].Value) > 6)
            //        {
            //            e.Cancel = true;
            //        }
            //    }
            //}
        }

        void m_GridHandle_Row_Validated(DataGridViewRow row)
        {
            if (Globals.DB_GetValue<int>(row.Cells["Detail_TotalMonth"].Value) > 6)
                row.ReadOnly = true;
        }

        private void LoadData()
        {
            FormGlobals.App_ProgressShow(delegate()
            {
                DataSet _ds = _wcfEmployee.Employee_NghiThaiSanList(out itemCount, branch_ID, department_ID, currPage, pageSize);
                dtTS = _ds.Tables[0];
                if (!dtTS.Columns.Contains("Detail_PositionName"))
                    dtTS.Columns.Add(new DataColumn("Detail_PositionName"));
                dgvEmployeeList.DataSource = dtTS;
                

                //
                switch (cboSoThang.SelectedIndex)
                {
                    case 1:
                        dtTS.DefaultView.RowFilter = "Detail_TotalMonth =7"; // =7 xử lý checkbox
                        break;
                    case 2:
                        dtTS.DefaultView.RowFilter = "Detail_TotalMonth > 7"; //> 7 xử lý checkbox
                        break;
                    default:
                        dtTS.DefaultView.RowFilter = ""; //Lấy tất
                        break;
                }

                //

                foreach (DataGridViewRow row in dgvEmployeeList.Rows)
                {
                    string Position_Name = Detail_Controller.Instance().GetPositionName(Convert.ToDateTime(row.Cells["Detail_FromDate"].Value), Convert.ToDateTime(row.Cells["Detail_ToDate"].Value), row.Cells["Detail_InsBookNo"].Value.ToString(), Program.strBranchCode, Convert.ToInt32(row.Cells["Employee_ID"].Value));
                    row.Cells["Detail_PositionName"].Value = Position_Name;
                }
            }, "Lấy dữ liệu thai sản");
        }

        private void GetSelectedID()
        {
            dgvEmployeeList.EndEdit();
            foreach (DataGridViewRow row in dgvEmployeeList.Rows)
            {
                if (!row.ReadOnly)
                {
                    if (Globals.Object_GetValue<bool>(row.Cells["Check"].Value))
                    {
                        if (!_selectedID.Contains("," + row.Cells["Employee_ID"].Value.ToString() + ","))
                            _selectedID += row.Cells["Employee_ID"].Value.ToString() + ",";
                    }
                    else
                    {
                        string sOld = "," + row.Cells["Employee_ID"].Value.ToString() + ",";
                        if (_selectedID.Contains(sOld))
                            _selectedID = _selectedID.Replace(sOld, ",");
                    }
                }
            }
        }


        private void dgvEmployeeList_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            dlgResult = DialogResult.OK;
            this.Close();
        }

        private void txtKeyWord_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
                btnFind_Click(null, null);
        }

        private void btnFind_Click(object sender, EventArgs e)
        {
            GetSelectedID();
            currPage = 0;
            LoadData();
        }

        private void btnNew_Click(object sender, EventArgs e)
        {
            GetSelectedID();
            if (dgvEmployeeList.SelectedRows.Count > 0)
                dgvEmployeeList_CellDoubleClick(null, null);
        }

        private void frmChooseEmployeeList_FormClosing(object sender, FormClosingEventArgs e)
        {
            this.DialogResult = dlgResult;
        }

        private void ChkCheckAll_CheckedChanged(object sender, EventArgs e)
        {
            for (int i = 0; i < dgvEmployeeList.Rows.Count; i++)
            {
                if (Globals.DB_GetValue<int>(dgvEmployeeList.Rows[i].Cells["Detail_TotalMonth"].Value) == 7)
                    dgvEmployeeList.Rows[i].Cells["Check"].Value = chkAll.Checked;
            }
            GetSelectedID();
        }

        private void cboSoThang_SelectedIndexChanged(object sender, EventArgs e)
        {
            LoadData();
        }

        private void btnNew_Click_1(object sender, EventArgs e)
        {
            GetSelectedID();
            if (_selectedID.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries).Length > 0)
            {
                //
                LayDuLieu();
                //
                dlgResult = DialogResult.OK;
                this.Close();
            }
            else
            {
                MessageBox.Show("Chưa có dữ liệu nào được chọn!");
            }
        }

        private void LayDuLieu()
        {
            string[] _ArrID = SelectedID.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries);
            bool DaTangKy = false;

            DetailInfo _DetailInfo;

            for (int i = 0; i < _ArrID.Length; i++)
            {
                if (_ArrID[i].Length > 0)
                {
                    //Insert Detail:
                    _EmployeeID = Convert.ToInt32(_ArrID[i]);
                    EmployeeInfo _EmployeeInfo = _wcfEmployee.Employee_GetInfo(_EmployeeID);
                    PositionDetailInfo _PDInfo = _wcfPositionDetal.PositionDetail_GetInfo(_EmployeeID);
                    //_DetailID = 0;
                    _DetailInfo = new DetailInfo();
                    _DetailInfo.Detail_Documentid = DocumentId;
                    _DetailInfo.Detail_Insbookno = _EmployeeInfo.SIBookNo;
                    _DetailInfo.Detail_Employeecode = _EmployeeInfo.Code;

                    //Từ tháng đến tháng
                    _DetailInfo.Detail_Fromdate = new DateTime(_HeaderInfo.Document_Year, _HeaderInfo.Document_Month, 1);
                    _DetailInfo.Detail_Todate = new DateTime(_HeaderInfo.Document_Year, _HeaderInfo.Document_Month, 1);

                    //PA
                    _DetailInfo.Detail_Instypecode = "ON"; //ON lại
                    _DetailInfo.Detail_Medicalrate = BhytRate;
                    _DetailInfo.Detail_Unemployedrate = BhtnRate;
                    _DetailInfo.Detail_Socialrate = BhxhRate;

                    //
                    _DetailInfo.Detail_Oldbasicfactor = 0;
                    _DetailInfo.Detail_Oldpositionfactor = 0;
                    _DetailInfo.Detail_Oldoverfactor = 0;
                    _DetailInfo.Detail_Oldjobfactor = 0;
                    _DetailInfo.Detail_Oldareafactor = 0;
                    _DetailInfo.Detail_Oldamount = 0;

                    
                    //Mức cũ
                    //int JobFactorOldPercent = 0;
                    DataRow[] drArray = dtTS.Select("Employee_ID = " + _ArrID[i]);
                    if (drArray != null)
                        if (drArray.Length == 1)
                        {
                            //Lấy dữ liệu mức cũ
                            _DetailInfo.Detail_Oldbasicfactor = Convert.ToDecimal(drArray[0]["Detail_Oldbasicfactor"]);
                            _DetailInfo.Detail_Oldpositionfactor = Convert.ToDecimal(drArray[0]["Detail_Oldpositionfactor"]);
                            _DetailInfo.Detail_Oldoverfactor = Convert.ToDecimal(drArray[0]["Detail_Oldoverfactor"]);
                            _DetailInfo.Detail_Oldjobfactor = Convert.ToDecimal(drArray[0]["Detail_Oldjobfactor"]);
                            _DetailInfo.Detail_Oldareafactor = Convert.ToDecimal(drArray[0]["Detail_Oldareafactor"]);
                            _DetailInfo.Detail_Oldamount = Convert.ToDecimal(drArray[0]["Detail_Oldamount"]);
                            //
                            _DetailInfo.Detail_Oldjobfactor_Percent = Convert.ToInt32(drArray[0]["Detail_Oldjobfactor_Percent"]);
                            _DetailInfo.Detail_Oldoverfactor_Percent = Convert.ToInt32(drArray[0]["Detail_Oldoverfactor_Percent"]);
                            _DetailInfo.Detail_PositionName = Globals.DB_GetNull(drArray[0]["Detail_PositionName"], "").ToString();
                        }

                    //if (_PDInfo.BasicSalary > 0)
                    //hiepdh 10:35 nếu có ML cũ => on lại theo ML 
                    if(_DetailInfo.Detail_Oldamount > 0)
                    {
                        _DetailInfo.Detail_Newamount = _DetailInfo.Detail_Oldamount; // _PDInfo.BasicSalary;
                        _DetailInfo.Detail_Type = "ML";
                        //ko lấy mức cũ

                        _DetailInfo.Detail_Oldamount = 0;
                    }
                    else
                    {
                        _DetailInfo.Detail_Newbasicfactor = _DetailInfo.Detail_Oldbasicfactor;
                        _DetailInfo.Detail_Newpositionfactor = _DetailInfo.Detail_Oldpositionfactor;
                        _DetailInfo.Detail_Newoverfactor = _DetailInfo.Detail_Oldoverfactor;
                        _DetailInfo.Detail_Newareafactor = _DetailInfo.Detail_Oldareafactor;
                        _DetailInfo.Detail_Newjobfactor = _DetailInfo.Detail_Oldjobfactor;
                        _DetailInfo.Detail_Newoverfactor = _DetailInfo.Detail_Oldoverfactor;
                        _DetailInfo.Detail_Newoverfactor_Percent = _DetailInfo.Detail_Oldoverfactor_Percent;
                        _DetailInfo.Detail_Newjobfactor_Percent = _DetailInfo.Detail_Oldjobfactor_Percent;
                        _DetailInfo.Detail_Type = "HS";
                        //ko lấy mức cũ
                        _DetailInfo.Detail_Oldjobfactor = _DetailInfo.Detail_Oldbasicfactor = _DetailInfo.Detail_Oldpositionfactor = _DetailInfo.Detail_Oldoverfactor = _DetailInfo.Detail_Oldareafactor = _DetailInfo.Detail_Oldoverfactor_Percent = _DetailInfo.Detail_Oldjobfactor_Percent = 0;
                    }

                    _DetailInfo.Detail_Regioncode = "";
                    _DetailInfo.Detail_Hospitalcode = "";
                    _DetailInfo.Detail_Takecard = false;
                    _DetailInfo.Detail_Status = 2;
                    _DetailInfo.Detail_Description = "";

                    if (_DetailInfo.Detail_Fromdate == _DetailInfo.Detail_Todate)
                        _DetailInfo.Detail_Totalmonth = 0;
                    else if (_DetailInfo.Detail_Fromdate == _DetailInfo.Detail_Todate && _DetailInfo.Detail_Todate == ViewDate)
                        _DetailInfo.Detail_Totalmonth = 0;
                    else if ((_DetailInfo.Detail_Fromdate == ViewDate || _DetailInfo.Detail_Todate == ViewDate) && _DetailInfo.Detail_Fromdate < _DetailInfo.Detail_Todate)
                        _DetailInfo.Detail_Totalmonth = UISetting.GetMonth(_DetailInfo.Detail_Fromdate, _DetailInfo.Detail_Todate);
                    else
                        _DetailInfo.Detail_Totalmonth = UISetting.GetMonth(_DetailInfo.Detail_Fromdate, _DetailInfo.Detail_Todate) + 1;

                    if (!Detail_Controller.Instance().Detail_Exist(0, _DetailInfo.Detail_Insbookno, _DetailInfo.Detail_Fromdate, _DetailInfo.Detail_Todate, _DetailInfo.Detail_Instypecode, _DetailInfo.Detail_Oldamount, _DetailInfo.Detail_Oldbasicfactor, _DetailInfo.Detail_Oldpositionfactor, _DetailInfo.Detail_Oldoverfactor, _DetailInfo.Detail_Oldjobfactor, _DetailInfo.Detail_Newamount, _DetailInfo.Detail_Newbasicfactor, _DetailInfo.Detail_Newpositionfactor, _DetailInfo.Detail_Newoverfactor, _DetailInfo.Detail_Newjobfactor))
                    {
                        //_DetailID = 
                        Detail_Controller.Instance().Detail_Insert(_DetailInfo);
                    }
                }
            }

            //if (_ArrID.Length > 0)
            //    txtDocument_Period.Text = (Convert.ToInt32(txtDocument_Period.Text) + 1).ToString();
        }
    }
}

